from supabase import create_client, Client
import os
from dotenv import load_dotenv
class TechArticleService:
    def __init__(self):
        load_dotenv()
        url:str = os.getenv('SUPABASE_URL')
        key:str = os.getenv('SUPABASE_KEY')
        self.client: Client = create_client(url, key)
    def get_articles(self, is_cn_generted=True, is_published=False):
        query = self.client.from_('tech_articles').select('*')
        if is_cn_generted:
            query = query.not_.is_('cn_content', 'null')
        else:   
            query = query.is_('cn_content', 'null')
        if not is_published:
            query = query.or_('basic_info.is.null, basic_info->>published.eq.0')
        tech_articles = query.execute()
        # print(tech_articles)
        return tech_articles.data
    def update_cn_article(self, id, markdownContent):
        title, content = TechArticleService.extract_title_and_content(markdownContent)
        content = {
            "title": title,
            "content": content}
        self.client.table('tech_articles').update({
                "cn_content": content
            }).eq('id', id).execute()
    def update_published(self, id):
        self.client.table('tech_articles').update({
                "basic_info": {
                    "published": 1
                }
            }).eq('id', id).execute()
        return True
    def upsert_article(self, articles):
        if len(articles) == 0:
            return False
        self.client.table('tech_articles').upsert(articles, on_conflict='title').execute()
        return True
    def get_articles_not_titles(self, titles):
        query = self.client.from_('tech_articles').select('title')\
            .in_('title', titles)
        tech_articles = query.execute()
        db_articels = tech_articles.data
        db_titles = {article['title'] for article in db_articels}
        missing_titles = [title for title in titles if title not in db_titles]
        return missing_titles
        
    @staticmethod
    def extract_title_and_content(md_text: str):
        lines = md_text.strip().splitlines()
        title = ""
        content_lines = []

        for i, line in enumerate(lines):
            if line.startswith("# ") or line.startswith("## "):
                title = line[2:].strip()
                content_lines = lines[i+1:]  # 其余为正文内容
                break

        content = "\n".join(content_lines).strip()
        return title, content
if __name__ == '__main__':
    tech_article_service = TechArticleService()
    tech_article_service.get_articles()